//
//  ChatTextTableViewCell.m
//  TIMChat
//
//  Created by AlexiChen on 16/3/10.
//  Copyright © 2016年 AlexiChen. All rights reserved.
//

#import "ChatTableViewCell.h"
#import "NSMutableAttributedString+MHMoment.h"


//==============================================================
@implementation ChatTextTableViewCell

// 只创建，外部统一添加
- (UIView *)addElemContent
{
    _chatText = [[YYLabel alloc] init];
    _chatText.textAlignment = NSTextAlignmentLeft;
    _chatText.numberOfLines = 0;
//    _chatText.font = MHRegularFont_14;
    _chatText.lineBreakMode = NSLineBreakByWordWrapping;
    _chatText.userInteractionEnabled = YES;
    return _chatText;
}

- (void)configContent
{
    [super configContent];
    
    _chatText.font = [_msg textFont];
    _chatText.textColor = [_msg textColor];
    
    TIMTextElem *elem = (TIMTextElem *)[_msg.msg getElem:0];
    NSMutableAttributedString *textAttr = [[NSMutableAttributedString alloc] initWithString:[elem text]];
    textAttr.yy_font = MHRegularFont_14;
    textAttr.yy_color = [_msg textColor];
    [textAttr mh_regexContentWithWithEmojiImageFontSize:14];
    _chatText.attributedText = textAttr.copy;
}

@end
//==============================================================
@implementation ChatImageTableViewCell

// 只创建，外部统一添加
- (UIView *)addElemContent
{
    _chatImage = [[UIImageView alloc] init];
    _chatImage.backgroundColor = [UIColor flatGrayColor];
    _chatImage.userInteractionEnabled = YES;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapImage:)];
    tap.numberOfTapsRequired = 1;
    tap.numberOfTouchesRequired = 1;
    [_chatImage addGestureRecognizer:tap];

    
    return _chatImage;
}

//-(void)configContent
//{
//    
//    
//}

- (void)onTapImage:(UITapGestureRecognizer *)tap
{
    if (tap.state == UIGestureRecognizerStateEnded)
    {
        [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
        
        UIView *keyWindow = [UIApplication sharedApplication].keyWindow;
        CGRect rect = [_chatImage relativePositionTo:keyWindow];
        ChatImageBrowserView *view = [[ChatImageBrowserView alloc] initWithPicModel:_msg thumbnail:_chatImage.image fromRect:rect];
        [keyWindow addSubview:view];
    }
    
}

- (void)configContent
{
    [super configContent];
    
    TIMImageElem *elem = (TIMImageElem *)[_msg.msg getElem:0];
    
    __weak UIImageView *wci = _chatImage;
    [elem asyncThumbImage:^(NSString *path, UIImage *image, BOOL succ, BOOL isAsync) {
        wci.image = image ? image : [UIImage imageNamed:@"default_image"];
    } inMsg:_msg];
    _contentBack.image = [UIImage imageWithColor:[UIColor clearColor]];
}

- (NSArray *)showMenuItems
{
    NSMutableArray *array = [NSMutableArray arrayWithArray:[super showMenuItems]];
    
    if (_msg.status != EIMAMsg_SendFail && ![_msg isMineMsg])
    {
        UIMenuItem *saveItem = [[UIMenuItem alloc] initWithTitle:@"保存" action:@selector(saveImage:)];
        [array addObject:saveItem];
    }
    return array;
}

- (void)saveImage:(UIMenuItem *)item
{
    UIImageWriteToSavedPhotosAlbum(_chatImage.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (!error)
    {
        [[HUDHelper sharedInstance] tipMessage:@"已保存到相册"];
    }
    else
    {
        [[HUDHelper sharedInstance] tipMessage:[NSString stringWithFormat:@"保存失败 %@",error]];
    }
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    BOOL can = [super canPerformAction:action withSender:sender] || action == @selector(saveImage:);
    return can;
}

@end

//==============================================================
@implementation ChatSoundTableViewCell

- (void)dealloc
{
    
}

// 只创建，外部统一添加
- (UIView *)addElemContent
{
    _soundButton = [[ImageTitleButton alloc] init];
    _soundButton.titleLabel.textAlignment = NSTextAlignmentCenter;
    [_soundButton addTarget:self action:@selector(onPlaySound) forControlEvents:UIControlEventTouchUpInside];
    _soundButton.userInteractionEnabled = YES;
    return _soundButton;
}

- (void)configSendingTips
{
    [super configSendingTips];
    if (_msg.status == EIMAMsg_WillSending)
    {
        _elemContentRef.hidden = YES;
        [_contentBack startGlowing];
    }
    else
    {
        _elemContentRef.hidden = NO;
        [_contentBack stopGlowing];
    }
    
}

- (void)configContent
{
    [super configContent];
    
    [self stopPlaySound];
    
    // 停止上一次的播放
    [_soundButton.imageView stopAnimating];
    
    BOOL isMine = [_msg isMineMsg];
    _soundButton.style = isMine ? ETitleLeftImageRight : EImageLeftTitleRight;
    
//    _soundButton.style = isMine ? EImageLeftTitleRightLeft : EImageLeftTitleRightLeft;
    [_soundButton setImage:isMine ? [UIImage imageNamed:@"my_voice3"] : [UIImage imageNamed:@"other_voice3"] forState:UIControlStateNormal];
    [_soundButton setTitleColor:[_msg textColor] forState:UIControlStateNormal];
    
    TIMSoundElem *elem = (TIMSoundElem *)[_msg.msg getElem:0];
    [_soundButton setTitle:[NSString stringWithFormat:@"%d''", elem.second] forState:UIControlStateNormal];
    
}

- (void)startPlaySoundAnimating
{
     BOOL isMine = [_msg isMineMsg];
    if (isMine)
    {
        _soundButton.imageView.animationImages = @[[UIImage imageNamed:@"my_voice1"], [UIImage imageNamed:@"my_voice2"], [UIImage imageNamed:@"my_voice3"]];
    }
    else
    {
        _soundButton.imageView.animationImages = @[[UIImage imageNamed:@"other_voice1"], [UIImage imageNamed:@"other_voice2"], [UIImage imageNamed:@"other_voice3"]];
    }

    _soundButton.imageView.animationDuration = 0.5;
    _soundButton.imageView.animationRepeatCount = 0;
    [_soundButton.imageView startAnimating];
}

- (void)stopPlaySoundAnimating
{
    [_soundButton.imageView stopAnimating];
    _soundButton.imageView.animationImages = nil;
}

//-(void) startSoundAnimation
//{
//    [_soundButton.imageView startAnimating];
//}

- (void)startPlaySound
{
    [self startPlaySoundAnimating];
    TIMSoundElem *elem = (TIMSoundElem *)[_msg.msg getElem:0];
    __weak ChatSoundTableViewCell *ws = self;
    
    NSString *cache = [PathUtility getCachePath];
    NSString *loginId = [[TIMManager sharedInstance] getLoginUser];
    NSString *audioDir = [NSString stringWithFormat:@"%@/%@",cache,loginId];
    BOOL isDir = FALSE;
    BOOL isDirExist = [[NSFileManager defaultManager] fileExistsAtPath:audioDir isDirectory:&isDir];
    if (!(isDir && isDirExist))
    {
        BOOL isCreateDir = [PathUtility createDirectoryAtCache:loginId];
        if (!isCreateDir) {
            return;
        }
    }
    NSString *path = [NSString stringWithFormat:@"%@/%@/%@",cache,loginId,elem.uuid];
    if ([PathUtility isExistFile:path])
    {
        NSURL *url = [NSURL fileURLWithPath:path];
        [[ChatSoundPlayer sharedInstance] playWithUrl:url finish:^{
            [ws stopPlaySoundAnimating];
        }];
    }
    else
    {
        [elem getSound:path succ:^{
            NSURL *url = [NSURL fileURLWithPath:path];
            [[ChatSoundPlayer sharedInstance] playWithUrl:url finish:^{
                [ws stopPlaySoundAnimating];
            }];
        } fail:^(int code, NSString *msg) {
            NSLog(@"path--->%@",path);
            [[HUDHelper sharedInstance] tipMessage:[NSString stringWithFormat:@"播放语音失败:%@，path=%@", IMALocalizedError(code, msg),path]];
        }];
    }
}

- (void)stopPlaySound
{
    [self stopPlaySoundAnimating];
    [[ChatSoundPlayer sharedInstance] stopPlay];
}

- (void)onPlaySound
{
//
    if (!_soundButton.imageView.isAnimating)
    {
        [self startPlaySound];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self startPlaySoundAnimating];
          
        });
        
    }
    else
    {
        // 正在播放，再次点击，则停止播放
        [self stopPlaySound];
    }
//    if ([ChatSoundPlayer sharedInstance].soundPlayer.currentTime > 0) {
//        if(![ChatSoundPlayer sharedInstance].soundPlayer.isPlaying)
//        {
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [self startPlaySoundAnimating];
//            });
//
//        }else
//        {
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [self stopPlaySoundAnimating];
//            });
//        }
//        [[ChatSoundPlayer sharedInstance] playOrPause];
//
//    }else
//    {
//        [self startPlaySound];
//    }
    
}



@end

//==============================================================
@implementation ChatFileTableViewCell

// 只创建，外部统一添加
- (UIView *)addElemContent
{
    _filePanel = [[UIView alloc] init];
    
    _fileIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"input_image"]];
    [_fileIcon setFrame:CGRectMake(kDefaultMargin/2, kDefaultMargin/2, 60, 60)];
    [_filePanel addSubview:_fileIcon];
    
    _fileName = [[UILabel alloc] initWithFrame:CGRectMake(_fileIcon.bounds.size.width+kDefaultMargin, kDefaultMargin/2, 120, _fileIcon.bounds.size.height * 2/3)];
    _fileName.numberOfLines = 0;
    _fileName.lineBreakMode = NSLineBreakByTruncatingMiddle;
    _fileName.font = kAppSmallTextFont;
    [_filePanel addSubview:_fileName];
    
    _fileSize = [[UILabel alloc] initWithFrame:CGRectMake(_fileIcon.bounds.size.width+kDefaultMargin, _fileName.origin.y+_fileName.size.height, 100, _fileIcon.bounds.size.height * 1/3)];
    _fileSize.font = kAppSmallTextFont;
    [_filePanel addSubview:_fileSize];
    
    return _filePanel;
}

- (void)configContent
{
    [super configContent];
    
    TIMFileElem *elem = (TIMFileElem *)[_msg.msg getElem:0];
    NSString *fileSize = [self calculSize:elem.fileSize];
    NSString *fileName = [elem.filename lastPathComponent];
    _fileName.text = fileName;
    _fileSize.text = fileSize;
    
}

//计算文件大小
- (NSString *)calculSize:(NSInteger)size
{
    int loopCount = 0;
    int mod=0;
    while (size >=1024)
    {
        mod = size%1024;
        size /= 1024;
        loopCount++;
        if (loopCount > 4)
        {
            break;
        }
    }
    
    CGFloat rate=1;
    int loop = loopCount;
    while (loop--)
    {
        rate *= 1000.0;
    }
    CGFloat fSize = size + (CGFloat)mod/rate;
    NSString *sizeUnit;
    switch (loopCount)
    {
        case 0:
            sizeUnit = [[NSString alloc] initWithFormat:@"%.0fB",fSize];
            break;
        case 1:
            sizeUnit = [[NSString alloc] initWithFormat:@"%0.1fKB",fSize];
            break;
        case 2:
            sizeUnit = [[NSString alloc] initWithFormat:@"%0.2fMB",fSize];
            break;
        case 3:
            sizeUnit = [[NSString alloc] initWithFormat:@"%0.3fGB",fSize];
            break;
        case 4:
            sizeUnit = [[NSString alloc] initWithFormat:@"%0.4fTB",fSize];
            break;
        default:
            break;
    }
    return sizeUnit;
}

- (NSArray *)showMenuItems
{
    NSMutableArray *array = [NSMutableArray arrayWithArray:[super showMenuItems]];
    
    if (_msg.status != EIMAMsg_SendFail && ![_msg isMineMsg])
    {
        UIMenuItem *downloadItem = [[UIMenuItem alloc] initWithTitle:@"下载" action:@selector(downloadItem:)];
        [array addObject:downloadItem];
    }
    return array;
}

- (void)downloadItem:(id)sender
{
    DebugLog(@"downloadItem");
    
    TIMFileElem *elem = (TIMFileElem *)[_msg.msg getElem:0];
    
    if (!(elem.uuid && elem.uuid.length > 0))
    {
        [[HUDHelper sharedInstance] syncStopLoadingMessage:@"文件uuid为空"];
        return;
    }
    
    NSString *cachesPaths =[PathUtility getCachePath];
    NSString *fileName=[cachesPaths stringByAppendingPathComponent:[elem.filename lastPathComponent]];

    [[HUDHelper sharedInstance] syncLoading:@"正在下载"];

    [elem getFile:fileName succ:^{
        [[HUDHelper sharedInstance] syncStopLoading];
        
//        [data writeToFile:fileName atomically:YES];
        
        DebugLog(@"save path = %@", cachesPaths);
        NSString *msg = [[NSString alloc] initWithFormat:@"下载成功，文件已保存到%@",cachesPaths];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:msg delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    } fail:^(int code, NSString *msg) {
        [[HUDHelper sharedInstance] syncStopLoadingMessage:IMALocalizedError(code, msg)];
    }];
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    BOOL can = [super canPerformAction:action withSender:sender] || action == @selector(downloadItem:);
    return can;
}
@end
//==============================================================
#define kMomentLimitWidth MHMomentCommentViewWidth() * 0.8 - 20
@implementation ChatVideoTableViewCell

- (UIView *)addElemContent
{
    _videoPanel = [[MicroVideoPlayView alloc] initWithFrame:CGRectMake(0, 0, 150, 100)];
    return _videoPanel;
}

- (void)configContent
{
    [super configContent];
    
    [_videoPanel setMessage:_msg];
}

@end


@implementation ChatCustomVideoImageCell


//-(UIView *)sizeWith:(CGSize)size
//{
//    return CGSizeMake(, <#CGFloat height#>)
//}
-(UIView *)addElemContent
{
    /// 正文
    _containerView = [[UIView alloc] init];
    _containerView.backgroundColor = [UIColor whiteColor];
    _containerView.cornerRadius = 11.0f;
    _containerView.masksToBounds = YES;
    YYLabel *contentLable = [[MHYYCopyLabel alloc] init];
    contentLable.backgroundColor = self.contentView.backgroundColor;
    /// 垂直方向顶部对齐
    contentLable.textVerticalAlignment = YYTextVerticalAlignmentTop;
    /// 异步渲染和布局
    contentLable.displaysAsynchronously = NO;
    /// 利用textLayout来设置text、font、textColor...
    contentLable.ignoreCommonProperties = YES;
    contentLable.fadeOnAsynchronouslyDisplay = NO;
    contentLable.fadeOnHighlight = NO;
//    contentLable.preferredMaxLayoutWidth = kMomentLimitWidth;
//    contentLable.lineBreakMode = NSLineBreakByTruncatingTail;
//    contentLable.numberOfLines = 2;
    [_containerView addSubview:contentLable];
    self.contentLable = contentLable;
    
    
    
    YYLabel *anserLable = [[YYLabel alloc] init];
    anserLable.backgroundColor = self.contentView.backgroundColor;
    /// 垂直方向顶部对齐
    anserLable.textVerticalAlignment = YYTextVerticalAlignmentTop;
    /// 异步渲染和布局
    anserLable.displaysAsynchronously = NO;
    /// 利用textLayout来设置text、font、textColor...
    anserLable.ignoreCommonProperties = YES;
    anserLable.fadeOnAsynchronouslyDisplay = NO;
    anserLable.fadeOnHighlight = NO;
//    anserLable.preferredMaxLayoutWidth = kMomentLimitWidth;
    [_containerView addSubview:anserLable];
    self.anserLable = anserLable;
    
    
    /// videoView
    MHMomentVideoView *videoView = [MHMomentVideoView videoView];
    self.videoView = videoView;
    [_containerView addSubview:videoView];
    
    /// 位置
    YYLabel *locationLable = [[YYLabel alloc] init];
    locationLable.backgroundColor = self.contentView.backgroundColor;
    /// 垂直方向中心对齐
    locationLable.textVerticalAlignment = YYTextVerticalAlignmentCenter;
    /// 异步渲染和布局
    locationLable.displaysAsynchronously = NO;
    /// 利用textLayout来设置text、font、textColor...
    locationLable.ignoreCommonProperties = NO;
    locationLable.fadeOnAsynchronouslyDisplay = NO;
    locationLable.fadeOnHighlight = NO;
    [_containerView addSubview:locationLable];
    self.locationLable = locationLable;

    return _containerView;
}

-(void)configContent
{

    
    if (self.moment) {
        [self bindWithMoment:self.moment];
        self.contentLable.textLayout = self.contentLableLayout;
        self.contentLable.size = self.contentLableLayout.textBoundingSize;
        self.contentLable.frame = self.contentLableFrame;
        self.anserLable.textLayout = self.anserLableLayout;
        self.anserLable.size = self.anserLableLayout.textBoundingSize;
        self.anserLable.frame = self.anserLableFrame;
        self.videoView.hidden = (self.moment.type == MHMomentExtendTypeAsk);
        self.videoView.frame = self.videoViewFrame;
        if (self.moment.videoInfo) {
            [self.videoView.coverView yy_setImageWithURL:self.moment.videoInfo.coverURL placeholder:MHDefaultAvatar(MHDefaultAvatarTypeDefualt)];
            self.videoView.playBtn.hidden = NO;
            if (self.moment.redInfo) {
                self.videoView.redPacketBtn.hidden = NO;
                NSString *suff= @"";
                switch (self.moment.redInfo.type) {
                    case RedPacketInCircle:
                        suff = @"qn";
                        break;
                    case RedPacketNearby:
                        suff = @"fj";
                        break;
                    case RedPacketShare:
                        suff = @"wx";
                        break;
                    default:
                        break;
                }
                
                [self.videoView.redPacketBtn setImage:[UIImage imageNamed:[NSString stringWithFormat:@"ic_chat_%@",suff]] forState:0];
            }else
            {
                self.videoView.redPacketBtn.hidden = YES;
            }
            
            
            
            
            
        }else
        {
             MHPicture *pic =[self.moment.picInfos firstObject];
            [self.videoView.coverView yy_setImageWithURL:[NSURL URLWithString:pic.fullPath] placeholder:MHDefaultAvatar(MHDefaultAvatarTypeDefualt)];
            self.videoView.playBtn.hidden = YES;
             self.videoView.redPacketBtn.hidden = YES;
        }

        self.locationLable.textLayout = self.locationLableLayout;
        self.locationLable.frame = self.locationLableFrame;
    }
}

-(MHMoment *)moment
{
    if (!_moment) {
        TIMCustomElem *customElem= [_msg.msg getElem:0];
        NSDictionary *dictJson = [NSJSONSerialization JSONObjectWithData:customElem.data options:NSJSONReadingMutableContainers error:nil];
        NSString *dict = [dictJson objectForKey:@"actionParam"];
        if (!dict) {
            return nil;
        }
        NSData *objectData = [dict dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
                                                             options:NSJSONReadingMutableContainers
                                                               error:nil];
        
        if (dict) {
            MHMoment *moment = [MHMoment yy_modelWithJSON:json];
            _moment = moment;
        }else
        {
            _moment = nil;
        }
    }
    return _moment;
}

- (CGRect)anserLableFrame
{
    CGFloat contentLableX = MHChatContentLeftOrRightInset;
     BOOL isAnser =  (MHStringIsNotEmpty(self.moment.recentQA.questionContent) && MHStringIsNotEmpty(self.moment.recentQA.answerContent));
    return CGRectMake(contentLableX, CGRectGetMaxY(self.contentLableFrame) + (isAnser ?  MHMomentContentInnerMargin : 0), self.anserLableLayout.textBoundingSize.width, self.anserLableLayout.textBoundingSize.height);
}
-(CGRect)contentLableFrame
{
//     TIMCustomElem *customElem= [_msg.msg getElem:0];
    CGFloat contentLableX = MHChatContentLeftOrRightInset;
    CGFloat contentLableY = 10;
    return CGRectMake(contentLableX, contentLableY, self.contentLableLayout.textBoundingSize.width, self.contentLableLayout.textBoundingSize.height);
}

-(CGRect)videoViewFrame
{
    CGFloat videoViewX = self.contentLableFrame.origin.x;
    CGFloat videoViewY = CGRectGetMaxY(self.anserLableFrame) + MHMomentContentInnerMargin;
    return CGRectMake(videoViewX, videoViewY, MHMomentCommentViewWidth() * 0.8 - 20 , 147);
}

-(CGRect)locationLableFrame
{
//     TIMCustomElem *customElem= [_msg.msg getElem:0];
    CGFloat locationLableX = self.contentLableFrame.origin.x;
   //BOOL isLo =  (MHStringIsNotEmpty(self.moment.recentQA.questionContent) && MHStringIsNotEmpty(self.moment.recentQA.answerContent));
    CGFloat locationLableY = CGRectGetMaxY(self.videoViewFrame) + (self.moment.location.isShowLocation ?  MHMomentContentInnerMargin : 0);
    return CGRectMake(locationLableX, locationLableY, self.locationLableLayout.textBoundingSize.width , 25);
}


-(void) bindWithMoment:(MHMoment *)moment
{

    CGFloat limitWidth = MHMomentCommentViewWidth() * 0.8 - 20;

    YYTextBorder *border = [YYTextBorder new];
    border.cornerRadius = 0;
    border.insets = UIEdgeInsetsMake(0, -1, 0, -1);
    border.fillColor = MHMomentTextHighlightBackgroundColor;


    YYTextContainer *singleRowContainer = [YYTextContainer containerWithSize:YYTextContainerMaxSize];
    singleRowContainer.maximumNumberOfRows = 1;

    if (moment.recentType != MHRecentContentTypeAsk && MHStringIsEmpty(moment.recentQA.questionContent) ) {
        if (MHStringIsNotEmpty(moment.text)){
            NSMutableAttributedString *textAttr = [[NSMutableAttributedString alloc] initWithString:moment.text];
            textAttr.yy_font = MHMomentContentFont;
            textAttr.yy_color = MHMainTextColor;
            textAttr.yy_alignment = NSTextAlignmentLeft;
            [textAttr mh_regexContentWithWithEmojiImageFontSize:15];
            YYTextContainer *contentLableContainer = [YYTextContainer containerWithSize:CGSizeMake(limitWidth, MAXFLOAT)];
            contentLableContainer.maximumNumberOfRows = 2;
//            contentLableContainer.truncationType =  YYTextTruncationTypeEnd;
            contentLableContainer.truncationType = YYTextTruncationTypeEnd;
            contentLableContainer.truncationToken = [[NSAttributedString alloc] initWithString:@"..."];
            
            YYTextLayout *contentLableLayout = [YYTextLayout layoutWithContainer:contentLableContainer text:textAttr.copy];
            self.contentLableLayout = contentLableLayout;
            
//            self.contentLable.lineBreakMode = NSLineBreakByTruncatingTail;
        }
    }else
    {
        //与我相关，向我提问 ，发表后的样子
        //            moment.recentQA.answerContent =  @"222";
        if (MHStringIsNotEmpty(moment.recentQA.questionContent)){
            NSMutableAttributedString *textAttr = [[NSMutableAttributedString alloc] initWithString:moment.recentQA.questionContent];
            textAttr.yy_font = MHMomentContentFont;
            textAttr.yy_color = MHMomentContentTextColor;
            textAttr.yy_alignment = NSTextAlignmentLeft;
            NSMutableAttributedString *askedAttr;
            BOOL isReplay = MHStringIsNotEmpty(moment.recentQA.answerContent);
             NSString *askString =  isReplay ? [NSString stringWithFormat:@"%@提问:",moment.recentQA.questionUserName] : [NSString stringWithFormat:@"向%@提问:", moment.recentQA.answerUserName];
            if (moment.recentQA.answerUserName.length > 0) {
                askedAttr = [[NSMutableAttributedString alloc] initWithString:askString];
                askedAttr.yy_color = MHMomentAskTextColor;
                askedAttr.yy_font = MHMomentScreenNameFont;
                askedAttr.yy_alignment = NSTextAlignmentLeft;
                [textAttr insertAttributedString:askedAttr atIndex:0];
            }
            /// 去正则匹配
    
            [textAttr mh_regexContentWithWithEmojiImageFontSize:15];
    
            YYTextContainer *contentLableContainer = [YYTextContainer containerWithSize:CGSizeMake(limitWidth, MAXFLOAT)];
            contentLableContainer.maximumNumberOfRows = 2;
            contentLableContainer.truncationType = YYTextTruncationTypeEnd;
            contentLableContainer.truncationToken = [[NSAttributedString alloc] initWithString:@"..."];
            YYTextLayout *contentLableLayout = [YYTextLayout layoutWithContainer:contentLableContainer text:textAttr.copy];
            self.contentLableLayout = contentLableLayout;
           
        }


        if (MHStringIsNotEmpty(moment.recentQA.questionContent) && MHStringIsNotEmpty(moment.recentQA.answerContent))
        {
            NSMutableAttributedString *textAttr = [[NSMutableAttributedString alloc] initWithString:moment.recentQA.answerContent];
            textAttr.yy_font = MHMomentContentFont;
            textAttr.yy_color = MHMomentContentTextColor;
            textAttr.yy_lineBreakMode = NSLineBreakByTruncatingTail;
            textAttr.yy_alignment = NSTextAlignmentLeft;
            UIFont *font = MHMomentCommentScreenNameFont;
            UIImage *quotationImage = [UIImage imageNamed:@"icon_message_quotation"];
            quotationImage = [UIImage imageWithCGImage:quotationImage.CGImage scale:[UIScreen screenScale] orientation:UIImageOrientationUp];

            NSMutableAttributedString *attachLikeText = [NSMutableAttributedString yy_attachmentStringWithContent:quotationImage contentMode:UIViewContentModeCenter attachmentSize:quotationImage.size alignToFont:font alignment:YYTextVerticalAlignmentCenter];
            NSMutableAttributedString *marginAttr = [[NSMutableAttributedString alloc] initWithString:@"  "];
            [attachLikeText appendAttributedString:marginAttr];

            [textAttr insertAttributedString:attachLikeText atIndex:0];
            //                }
            /// 去正则匹配
            [textAttr mh_regexContentWithWithEmojiImageFontSize:15];
            YYTextContainer *anserLableContainer = [YYTextContainer containerWithSize:CGSizeMake(limitWidth, MAXFLOAT)];
            anserLableContainer.maximumNumberOfRows = 2;
            YYTextLayout *anserLableLayout = [YYTextLayout layoutWithContainer:anserLableContainer text:textAttr.copy];
            self.anserLableLayout = anserLableLayout;

        }
    }

    if (moment.location.isShowLocation) {
        /// 富文本

//        UIImage *likeImage = [UIImage imageNamed:@"icon_theme_dividingline"];
//        likeImage = [UIImage imageWithCGImage:likeImage.CGImage scale:[UIScreen screenScale] orientation:UIImageOrientationUp];
//
//        NSMutableAttributedString *attachLikeText = [NSMutableAttributedString yy_attachmentStringWithContent:likeImage contentMode:UIViewContentModeCenter attachmentSize:likeImage.size alignToFont:MHRegularFont_10 alignment:YYTextVerticalAlignmentCenter];

        NSMutableAttributedString *location  = [[NSMutableAttributedString alloc] initWithString:@""];
//        [location appendAttributedString:attachLikeText];
//        [location appendAttributedString:[[NSMutableAttributedString alloc] initWithString:@"   "]];

        UIImage *locationImage = [UIImage imageNamed:@"icon_theme_maplocation"];
        locationImage = [UIImage imageWithCGImage:locationImage.CGImage scale:[UIScreen screenScale] orientation:UIImageOrientationUp];

        NSMutableAttributedString *attachLocation = [NSMutableAttributedString yy_attachmentStringWithContent:locationImage contentMode:UIViewContentModeCenter attachmentSize:locationImage.size alignToFont:MHRegularFont_10 alignment:YYTextVerticalAlignmentCenter];
        [location appendAttributedString:attachLocation];
        [location appendAttributedString:[[NSMutableAttributedString alloc] initWithString:@" "]];
        [location appendAttributedString:[[NSMutableAttributedString alloc] initWithString:moment.location.areaName]];
        location.yy_font = MHRegularFont_10;
        location.yy_color = MHMetionTextColor;
        /// 高亮
        YYTextHighlight *highlight = [YYTextHighlight new];
        [highlight setBackgroundBorder:border];
        /// 传递数据
        highlight.userInfo = @{MHMomentLocationNameKey : moment.location};
        [location yy_setTextHighlight:highlight range:location.yy_rangeOfAll];
        /// 布局
        YYTextLayout *locationLableLayout = [YYTextLayout layoutWithContainer:singleRowContainer text:location.copy];
        self.locationLableLayout = locationLableLayout;

    }
}

@end

//==============================================================
